package patterns.compositePattern;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Stack;

public class LeaderIterator implements Iterator<Staff> {
	private Stack<Iterator<Staff>> staffIterators;

	public LeaderIterator(Iterator<Staff> iterator) {
		staffIterators = new Stack<>();
		staffIterators.push(iterator);
	}

	@Override
	public boolean hasNext() {
		if (staffIterators.isEmpty()) {
			return false;
		} else {
			Iterator<Staff> iterator = staffIterators.peek();
			if (!iterator.hasNext()) {
				staffIterators.pop();
				hasNext();
			} else {
				return true;
			}
		}
		return false;
	}

	@Override
	public Staff next() {
		if (!hasNext()) {
			return null;
		} else {
			Iterator<Staff> iterator = staffIterators.peek();
			Staff staff = iterator.next();
			if (staff instanceof LeaderStaff) {
				staffIterators.push(staff.createIterator());
			}
			return staff;
		}
	}

}
